
package com.rocksdata.mc.ui.activity;

import java.util.List;

import org.xutils.view.annotation.ContentView;
import org.xutils.view.annotation.Event;
import org.xutils.view.annotation.ViewInject;


import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.os.Handler;
import android.view.View;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.TextView;
import android.widget.Toast;

import com.ctz.commonframe.ui.BaseActivity;
import com.ctz.commonframe.ui.view.LockPatternView;
import com.ctz.commonframe.utils.LockPatternUtils;
import com.ctz.commonframe.utils.SharedPrefrencesUtil;
import com.rocksdata.mc.R;
import com.rocksdata.mc.SharedPreferencesKey;
import com.rocksdata.mc.business.BusinessManager;
import com.rocksdata.mc.business.UserInfoManager;

@ContentView(R.layout.activity_gesturepassword_unlock)
public class GesturePasswordUnlockActivity extends BaseActivity {
    private static final String[] TIPS = {"请绘制手势密码","请绘制旧密码"};

    public static final int MODE_DEFAULT = 0;
    public static final int MODE_MODIFY_PASSWORD = 1;

	@ViewInject(R.id.gesturepwd_unlock_lockview)
	private LockPatternView mLockPatternView;
	@ViewInject(R.id.gesturepwd_unlock_text)
	private TextView mHeadTextView;
	@ViewInject(R.id.gesturepwd_unlock_forget)
	private TextView gesturepwd_unlock_forget;

	private int mFailedPatternAttemptsSinceLastTimeout = 0;
	private CountDownTimer mCountdownTimer = null;
	private Handler mHandler = new Handler();
	private Animation mShakeAnim;
	private Toast mToast;
	private int index = 0;
	private String main_pd = "";
    private int mode;

	private void showToast(CharSequence message) {
		if (null == mToast) {
			mToast = Toast.makeText(this, message, Toast.LENGTH_SHORT);
		} else {
			mToast.setText(message);
		}

		mToast.show();
	}

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

        mode = getIntent().getIntExtra("mode", MODE_DEFAULT);
        mHeadTextView.setText(TIPS[mode]);
		mLockPatternView.setOnPatternListener(mChooseNewLockPatternListener);
		mLockPatternView.setTactileFeedbackEnabled(true);
		mShakeAnim = AnimationUtils.loadAnimation(this, R.anim.shake_x);
	}

//	@Override
//	protected void onResume() {
//		super.onResume();
//		if(SharedPrefrenceUtil.getGesturePassword()==null||SharedPrefrenceUtil.getGesturePassword().equals("")||SharedPrefrenceUtil.getGesturePassword().equals("0")){
//			startActivity(new Intent(this, GuideGesturePasswordActivity.class));
//			finish();
//		}
//	}

	@Override
	protected void onDestroy() {
		super.onDestroy();
		if (mCountdownTimer != null)
			mCountdownTimer.cancel();
	}

	@Event(value = {R.id.gesturepwd_unlock_forget})
	private void onClick(View view){
		switch (view.getId()){
			case R.id.gesturepwd_unlock_forget:
                new AlertDialog.Builder(GesturePasswordUnlockActivity.this)
                        .setTitle("提示")
                        .setMessage("您将退出当前账号，重新登陆后，可重新设置手势密码")
                        .setNegativeButton("确定", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                dialog.dismiss();
                                UserInfoManager.clearGesturePassword();
                                LockPatternUtils.getInstance(GesturePasswordUnlockActivity.this).clearLock();
								BusinessManager.getAccountManager().logout();
                                exit();
								startActivity(new Intent(GesturePasswordUnlockActivity.this, LoginActivity.class));
                            }
                        })
                        .setPositiveButton("取消", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                dialog.dismiss();
                            }
                        })
                        .create().show();
				break;
		}
	}

	private Runnable mClearPatternRunnable = new Runnable() {
		public void run() {
			mLockPatternView.clearPattern();
		}
	};

	protected LockPatternView.OnPatternListener mChooseNewLockPatternListener = new LockPatternView.OnPatternListener() {

		public void onPatternStart() {
			mLockPatternView.removeCallbacks(mClearPatternRunnable);
			patternInProgress();
		}

		public void onPatternCleared() {
			mLockPatternView.removeCallbacks(mClearPatternRunnable);
		}

		public void onPatternDetected(List<LockPatternView.Cell> pattern) {
			if (pattern == null)
				return;
			if(main_pd.equals(SharedPrefrencesUtil.getAboutUser(UserInfoManager.getCurrentUserId(), SharedPreferencesKey.KEY_GESTURE_PASSWORD, null))){
				mLockPatternView.setDisplayMode(LockPatternView.DisplayMode.Correct);
				if(mode == MODE_DEFAULT){
                    String className = getIntent().getStringExtra("className");
                    if(className != null) {
                        Intent intent = new Intent();
                        intent.setClassName(GesturePasswordUnlockActivity.this, className);
                        intent.putExtras(getIntent().getExtras());
                        // 打开新的Activity
                        startActivity(intent);
                    }
                    showToast("解锁成功");
                }else if(mode == MODE_MODIFY_PASSWORD){
                    startActivity(new Intent(GesturePasswordUnlockActivity.this, GesturePasswordCreateActivity.class));
                }
                finish();
			} else {
//				mLockPatternView.setDisplayMode(LockPatternView.DisplayMode.Wrong);
				if (pattern.size() >= LockPatternUtils.MIN_PATTERN_REGISTER_FAIL) {
					mFailedPatternAttemptsSinceLastTimeout++;
					int retry = LockPatternUtils.FAILED_ATTEMPTS_BEFORE_TIMEOUT - mFailedPatternAttemptsSinceLastTimeout;
					if (retry >= 0) {
						if (retry == 0){
							showToast("您已5次输错密码，请30秒后再试");
						}
						mHeadTextView.setText("密码错误，还可以再输入" + retry + "次");
						mHeadTextView.setTextColor(Color.RED);
						mHeadTextView.startAnimation(mShakeAnim);
					}

				} else {
					showToast("至少连" + LockPatternUtils.MIN_PATTERN_REGISTER_FAIL + "个点，请重试");
				}

				if (mFailedPatternAttemptsSinceLastTimeout >= LockPatternUtils.FAILED_ATTEMPTS_BEFORE_TIMEOUT) {
					mHandler.postDelayed(attemptLockout, 2000);
				} else {
					mLockPatternView.postDelayed(mClearPatternRunnable, 2000);
				}
				index = 0;
				main_pd = "";
			}
		}

		public void onPatternCellAdded(List<LockPatternView.Cell> pattern) {
			if(null != pattern){
		        int column = pattern.get(index).getColumn();
		        int row = pattern.get(index).getRow();
		        int num = numChange(column, row);
		        main_pd = main_pd + num + "";
		        index++;
		    }
		}

		private void patternInProgress() {
		}
	};
	Runnable attemptLockout = new Runnable() {

		@Override
		public void run() {
			mLockPatternView.clearPattern();
			mLockPatternView.setEnabled(false);
			mCountdownTimer = new CountDownTimer(LockPatternUtils.FAILED_ATTEMPT_TIMEOUT_MS + 1, 1000) {

				@Override
				public void onTick(long millisUntilFinished) {
					int secondsRemaining = (int) (millisUntilFinished / 1000) - 1;
					if (secondsRemaining > 0) {
						mHeadTextView.setText(secondsRemaining + " 秒后重试");
					} else {
						mHeadTextView.setText(TIPS[mode]);
						mHeadTextView.setTextColor(Color.WHITE);
					}

				}

				@Override
				public void onFinish() {
					mLockPatternView.setEnabled(true);
					mFailedPatternAttemptsSinceLastTimeout = 0;
				}
			}.start();
		}
	};
	private int numChange(int column,int row){
	    int num = 0;
	    if(row == 0){
	        num = column + 1;
	    }else if(row == 1){
	        num = column + 4;
	    }else if(row == 2){
	        num = column + 7;
	    }
	    return num;
	}

}
